package model.commands.keyboard;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

import model.RandomUtils;
import resources.ResourcesFactory;

public class KeyboardTypeRandomText extends KeyboardType {
	private Integer minChars = null;
	private Integer maxChars = null;
	private byte[] loremIpsum;

	public KeyboardTypeRandomText(){
		loadLoremIpsum();
	}
	
	private void loadLoremIpsum() {
		try {
			loremIpsum = Files.readAllBytes(Paths.get(ResourcesFactory.getLoremIpsumURI()));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("Error trying to load lorem ipsum file.");
		}
	}

	@Override
	public void execute() {
		try {
			int randomNumber = RandomUtils.getRandomNumber(minChars, maxChars+1);
			int iterations = randomNumber/loremIpsum.length; 
			if(iterations>0){
				for(int i=0;i<iterations;i++){
					type(new String(loremIpsum));
				}
			}
			byte[] text = Arrays.copyOf(loremIpsum, randomNumber%loremIpsum.length);  
			type(new String(text));
			propertyChangeSupport.firePropertyChange(EXECUTION_FINISHED, null, this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setParams(Object[] params) {
		minChars = ((Integer) params[0]);
		maxChars = ((Integer) params[1]);
		if(minChars == null){
			minChars = 0;
		}
		
		if(maxChars == null){
			maxChars = 255;
		}
	}

	public Integer getMinChars() {
		return minChars;
	}

	public Integer getMaxChars() {
		return maxChars;
	}
}
